package org.finegold.core.netty.core.websocket;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

/**
 * 抽象的文本通道输入处理器,该抽象主要约束泛型为{@link TextWebSocketFrame},开发者直接继承此抽象类重写
 * @author songkaikai
 * @since 2021/1/21
 */
public abstract class AbstractTextInboundHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private final ObjectMapper objectMapper;

    protected AbstractTextInboundHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    /**
     * 解析对象为String Json串
     * @param object 对象
     * @return {@link TextWebSocketFrame} 对象体
     * @throws JsonProcessingException json处理异常
     */
    protected TextWebSocketFrame resolveObjectAsString(Object object) throws JsonProcessingException {
        return new TextWebSocketFrame(objectMapper.writeValueAsString(object));
    }

}
